<template>
  <div class="app-container"> 
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="typeName" placeholder="请输入分类名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="typeOptions" :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--列表数据-->
        <pane size="84">
          <el-col>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="场馆" prop="deptId">
        <el-input
          v-model="queryParams.deptId"
          placeholder="请输入场馆"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="modelId">        
        <el-select v-model="queryParams.modelId" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in queryModelOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入设备位置/编码"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <template v-for="(p,i) in queryPropertyOptions" :key="i">
        <el-form-item :label="p.label" :prop="p.code" v-if="p.isSearch == 'Y'">
          <el-input-number v-model="form[p.code]" placeholder="请输入" v-if="p.formType == 'int'"/>
          <el-input-number v-model="form[p.code]" placeholder="请输入" v-else-if="p.formType == 'decimal'"/>
          <el-date-picker clearable v-if="p.formType == 'datetime'"
            v-model="form[p.code]"
            type="date"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择日期时间">
          </el-date-picker>
          <el-date-picker clearable v-if="p.formType == 'date'"
            v-model="form[p.code]"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期时间">
          </el-date-picker>
          <dict-input  v-model="queryParams[p.code]" :dictType='p.dsCode' formType="select" v-else-if="p.formType == 'radio' || p.formType == 'checkbox'"/>
          <ds-select  v-model="queryParams[p.code]" :dsCode='p.dsCode' v-else-if="p.formType == 'select'"/>
          <ds-tree  v-model="queryParams[p.code]" :dsCode='p.dsCode' v-else-if="p.formType == 'tree'"/>
          <el-input v-model="queryParams[p.code]" placeholder="请输入" v-else/>
        </el-form-item>
      </template>
      <el-form-item label="运行状态" prop="runStatus">
        <el-select v-model="queryParams.runStatus" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in run_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="使用状态" prop="useStatus">
        <el-select v-model="queryParams.useStatus" placeholder="请选择" clearable style="width:120px">
          <el-option
            v-for="dict in device_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="质保期限" style="width: 308px">
        <el-date-picker
          v-model="daterangeScrapDate"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-if="queryParams.typeId"
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:device:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:device:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:device:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="场馆" align="center" prop="deptId" />
      <el-table-column label="设备类型" align="center" prop="typeName" />
      <el-table-column label="型号" align="center" prop="modelName" />
      <el-table-column label="设备编码" align="center" prop="code" />
      <el-table-column label="设备位置" align="center" prop="position" />
      <template v-for="(c,i) in columns" :key="i">
        <el-table-column :label="c.label" align="center" :prop="c.code" v-if="c.visible">
            <list-tag  v-model="form[p.code]" :dictType='p.dsCode' formType="radio" v-if="c.formType == 'radio'"/>
        </el-table-column>
      </template>
      <el-table-column label="图例" align="center" prop="imgs" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.imgs" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="运行状态" align="center" prop="runStatus">
        <template #default="scope">
          <dict-tag :options="run_status" :value="scope.row.runStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="使用状态" align="center" prop="useStatus">
        <template #default="scope">
          <dict-tag :options="device_status" :value="scope.row.useStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="质保期限" align="center" prop="scrapDate" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:device:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:device:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="deviceRef" :model="form" :rules="rules" label-width="80px">
        <el-tabs v-model="tab">
          <el-tab-pane name="base" label="基本信息">
        <el-form-item label="场馆" prop="deptId">
          <el-input v-model="form.deptId" placeholder="请输入场馆" />
        </el-form-item>
        <el-form-item label="设备类型" prop="typeId">
          <el-tree-select @change="changeType"
            v-model="form.typeId"
            :data="typeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择设备类型"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="型号" prop="modelId">      
        <el-select v-model="form.modelId" placeholder="请选择" clearable>
          <el-option
            v-for="dict in modelOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
        </el-form-item>
        <el-form-item label="设备编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备编码" />
        </el-form-item>
        <el-form-item label="设备位置" prop="position">
          <el-input v-model="form.position" placeholder="请输入设备位置" />
        </el-form-item>
        <template v-for="(p,i) in propertyOptions" :key="i">
          <el-form-item :label="p.label" :prop="p.code">
            <el-input-number v-model="form[p.code]" placeholder="请输入" v-if="p.formType == 'int'"/>
            <el-input-number v-model="form[p.code]" placeholder="请输入" v-else-if="p.formType == 'decimal'"/>
            <el-date-picker clearable v-else-if="p.formType == 'datetime'"
              v-model="form[p.code]"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择日期时间">
            </el-date-picker>
            <el-date-picker clearable v-else-if="p.formType == 'date'"
              v-model="form[p.code]"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期">
            </el-date-picker>
            <dict-input  v-model="form[p.code]" :dictType='p.dsCode' formType="radio" v-else-if="p.formType == 'radio'"/>
            <dict-input  v-model="form[p.code]" :dictType='p.dsCode' formType="checkbox" v-else-if="p.formType == 'checkbox'"/>
            <ds-select  v-model="form[p.code]" :dsCode='p.dsCode' v-else-if="p.formType == 'select'"/>
            <ds-tree  v-model="form[p.code]" :dsCode='p.dsCode' v-else-if="p.formType == 'tree'"/>
            <el-input v-model="form[p.code]" type="text" rows="3" placeholder="请输入" v-else-if="p.formType == 'text'"/>
            <el-input v-model="form[p.code]" placeholder="请输入" v-else/>
          </el-form-item>
        </template>
        <el-form-item label="运行状态" prop="runStatus">
          <el-radio-group v-model="form.runStatus">
            <el-radio
              v-for="dict in run_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="使用状态" prop="useStatus">
          <el-radio-group v-model="form.useStatus">
            <el-radio
              v-for="dict in device_status"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="质保期限" prop="scrapDate">
            <el-date-picker clearable
              v-model="form.scrapDate"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期">
            </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="imgs" label="图例">
        <el-form-item label="图例" prop="imgs">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
        <el-form-item label="二维码" prop="qr">
          <image-upload v-model="form.imgs"/>
        </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Device">
import useAppStore from '@/store/modules/app'
import { listDevice, getDevice, delDevice, addDevice, updateDevice } from "@/api/base/device";
import { selectModel } from "@/api/base/model";
import { selectProperty } from "@/api/base/property";
import { listType } from "@/api/base/type";
import { dsData } from "@/api/dev/dataset";
import useDictStore from '@/store/modules/dict';
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

import DictInput from '@/components/FormInput/Dict';
import DsTree from '@/components/FormInput/Tree';
import DsSelect from '@/components/FormInput/Select';
import ListTag from '@/components/FormInput/Tag';

const { proxy } = getCurrentInstance();
const appStore = useAppStore()
const { device_status, run_status } = proxy.useDict('device_status', 'run_status');

const deviceList = ref([]);
const typeOptions = ref([]);
const modelOptions = ref([]);
const queryModelOptions = ref([]);
const queryPropertyOptions = ref([]);
const propertyOptions = ref([]);
const columns = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeScrapDate = ref([]);
const typeName = ref("");
const tab = ref("base");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orderByColumn: 't.id',
    isAsc: 'desc',
    deptId: null,
    sysId: null,
    typeId: null,
    modelId: null,
    code: null,
    position: null,
    pointX: null,
    pointY: null,
    pointZ: null,
    propInt1: null,
    propInt2: null,
    propInt3: null,
    propInt4: null,
    propInt5: null,
    propDc1: null,
    propDc2: null,
    propDc3: null,
    propStr1: null,
    propStr2: null,
    propStr3: null,
    propStr4: null,
    propStr5: null,
    propStr6: null,
    propStr7: null,
    propStr8: null,
    propDt1: null,
    propDt2: null,
    propD1: null,
    propD2: null,
    propText1: null,
    propText2: null,
    runStatus: null,
    useStatus: null,
    scrapDate: null,
    extCode: null,
    pfCode: null
  },
  rules: {
    deptId: [
      { required: true, message: "场馆不能为空", trigger: "blur" }
    ],
    sysId: [
      { required: true, message: "系统ID不能为空", trigger: "blur" }
    ],
    typeId: [
      { required: true, message: "类型ID不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "设备编码不能为空", trigger: "blur" }
    ],
    position: [
      { required: true, message: "设备位置不能为空", trigger: "blur" }
    ],
    runStatus: [
      { required: true, message: "设备状态不能为空", trigger: "change" }
    ],
    useStatus: [
      { required: true, message: "设备使用状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeScrapDate && '' != daterangeScrapDate) {
    queryParams.value.params["beginScrapDate"] = daterangeScrapDate.value[0];
    queryParams.value.params["endScrapDate"] = daterangeScrapDate.value[1];
  }
  listDevice(queryParams.value).then(response => {
    deviceList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}


/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

/** 根据名称筛选树 */
watch(typeName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.typeId = data.id;
  form.value.typeId = data.id;
  handleQuery();
  changeQueryType();
};

/** 更换设备类型 */
function changeQueryType(){
  selectModel({typeId: form.value.typeId}).then(response=>{
    queryModelOptions.value = response.rows;
  });
  
  selectProperty({typeId: form.value.typeId}).then(response=>{
    queryPropertyOptions.value = response.rows;
    let cols = [];
    response.rows.forEach(e=> {
      cols.push({visible: e.isSearch == 'Y', label: e.label, code:e.code, key: e.id});
      if(e.formType == 'select' || e.formType == 'tree'){
        loadDs(e.dsCode)
      }else{
        proxy.useDict(e.dsCode);
      }
    });
    columns.value = cols;
  });
}

/** 更换设备类型 */
function changeType(){  
  selectProperty({typeId: form.value.typeId}).then(response=>{
    propertyOptions.value = response.rows;
    for(let p in rules.value){
      if(p.substr(0,3) == 'prop'){
        rules.value[p] = null;
      }
    }
    response.rows.forEach(e=> {
      if(e.formType == 'select' || e.formType == 'tree'){
        loadDs(e.dsCode)
      }else{
        proxy.useDict(e.dsCode);
      }
      if(e.isRequired == 'Y'){
        rules.value[e.code] =  [
          { required: true, message: e.label + "不能为空", trigger: "blur" }
        ];
      }
    });
  });
}

/** 加载数据源 */
function loadDs(dsCode) {
    let dsKey = "ds_"+dsCode;
    const dicts = useDictStore().getDict(dsKey);
    if (!dicts) {
        dsData(dsCode).then(resp => {
            useDictStore().setDict(dsKey, resp.data);
        });
    }
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    typeId: null,
    modelId: null,
    code: null,
    position: null,
    pointX: null,
    pointY: null,
    pointZ: null,
    propInt1: null,
    propInt2: null,
    propInt3: null,
    propInt4: null,
    propInt5: null,
    propDc1: null,
    propDc2: null,
    propDc3: null,
    propStr1: null,
    propStr2: null,
    propStr3: null,
    propStr4: null,
    propStr5: null,
    propStr6: null,
    propStr7: null,
    propStr8: null,
    propDt1: null,
    propDt2: null,
    propD1: null,
    propD2: null,
    propText1: null,
    propText2: null,
    imgs: null,
    runStatus: '0',
    useStatus: '0',
    scrapDate: null,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    extCode: null,
    pfCode: null
  };
  if(queryParams.value.typeId){
    form.value.typeId = queryParams.value.typeId;
    changeType();
  }
  proxy.resetForm("deviceRef");
  tab.value = 'base';
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getDevice(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备信息";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deviceRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDevice(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的设备信息数据项？').then(function() {
    return delDevice(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/device/export', {
    ...queryParams.value
  }, `device_${new Date().getTime()}.xlsx`)
}


getList();
listType().then(response => {
  typeOptions.value = [];
  const data = { id: 0, name: '全部分类', children: [] };
  data.children = proxy.handleTree(response.data, "id", "parentId");
  typeOptions.value.push(data);
});
</script>
